/**
 * 定义如何从router跳转到page和api
 */
const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const util = require('../util');

module.exports = function(context) {
    // 注册如何实现跳转到定义
    context.subscriptions.push(vscode.languages.registerDefinitionProvider(['javascript'], {
        /**
         * 查找文件定义的provider
         * @param {*} document 
         * @param {*} position 
         * @param {*} token 
         */
        provideDefinition: function(document, position, token) {
            const fileName    = document.fileName;
            const workDir     = path.dirname(fileName);
            const line        = document.lineAt(position);
            const projectPath = util.getProjectPath(document);
            
            if (/app\/router\.js$/g.test(fileName)) {
                const result = /,\s*'?((page|api)\.[\w.]+?)'?\s*\)/g.exec(line.text);
                if (!result) return;
                const target = result[1];
                let destPath = `${projectPath}/app/controller/${target.replace(/\./g, '/')}.js`;
                if (fs.existsSync(destPath)) {
                    return new vscode.Location(vscode.Uri.file(destPath), new vscode.Position(0, 0));
                } else {
                    const tempPath = target.split('.');
                    const methodName = tempPath.pop();
                    destPath = `${projectPath}/app/controller/${tempPath.join('/')}.js`;
                    if (fs.existsSync(destPath)) {
                        const pos = util.findStrInFile(destPath, new RegExp(`(module\\.)?exports\\.${methodName}\\s*=`, 'g'));
                        return new vscode.Location(vscode.Uri.file(destPath), new vscode.Position(pos.row, pos.col));
                    } else {
                        util.showError('未找到相关文件！');
                    }
                }
            }
        }
    }));
};